import React, { useEffect, useState } from "react";
import { Card, Table, Tag, Space, Modal, Form, InputNumber, Switch, Select, Input, message } from "antd";
import type { ColumnsType } from "antd/es/table";
import { request } from "../../../utils/request";

interface PricingData {
  id: number;
  ai_person_id: number;
  ai_person_name: string;
  requires_subscription: boolean;
  subscription_price: string | null;
  per_use_price_subscriber: string | null;
  per_use_price_non_subscriber: string | null;
  free_quota_type: string;
  free_quota_subscriber: number | null;
  free_quota_non_subscriber: number | null;
  overage_price_subscriber: string | null;
  overage_price_non_subscriber: string | null;
  metadata: any;
  createdAt: string | null;
  updatedAt: string | null;
}

const { Option } = Select;

const AgentConfig: React.FC = () => {
  const [data, setData] = useState<PricingData[]>([]);
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState(false);
  const [current, setCurrent] = useState<PricingData | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchPricingData();
  }, []);

  const fetchPricingData = async () => {
    setLoading(true);
    try {
      const response = await request.get("/api/admin/agent/pricing");
      setData(response.data.list || []);
    } catch (error) {
      console.error("Failed to fetch pricing data:", error);
    } finally {
      setLoading(false);
    }
  };

  const openEdit = (record: PricingData) => {
    setCurrent(record);
    form.setFieldsValue({
      ai_person_id: record.ai_person_id,
      requires_subscription: record.requires_subscription,
      subscription_price: record.subscription_price ? Number(record.subscription_price) : undefined,
      per_use_price_subscriber: record.per_use_price_subscriber ? Number(record.per_use_price_subscriber) : undefined,
      per_use_price_non_subscriber: record.per_use_price_non_subscriber ? Number(record.per_use_price_non_subscriber) : undefined,
      free_quota_type: record.free_quota_type,
      free_quota_subscriber: record.free_quota_subscriber ?? 0,
      free_quota_non_subscriber: record.free_quota_non_subscriber ?? 0,
      overage_price_subscriber: record.overage_price_subscriber ? Number(record.overage_price_subscriber) : undefined,
      overage_price_non_subscriber: record.overage_price_non_subscriber ? Number(record.overage_price_non_subscriber) : undefined,
      metadata: record.metadata ? (typeof record.metadata === "string" ? record.metadata : JSON.stringify(record.metadata)) : "",
    });
    setEditing(true);
  };

  const handleCancel = () => {
    setEditing(false);
    setCurrent(null);
    form.resetFields();
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        ai_person_id: String(values.ai_person_id),
        requires_subscription: Boolean(values.requires_subscription),
        subscription_price: values.subscription_price ?? 0,
        per_use_price_subscriber: values.per_use_price_subscriber ?? null,
        per_use_price_non_subscriber: values.per_use_price_non_subscriber ?? 0,
        free_quota_type: values.free_quota_type,
        free_quota_subscriber: values.free_quota_subscriber ?? 0,
        free_quota_non_subscriber: values.free_quota_non_subscriber ?? 0,
        overage_price_subscriber: values.overage_price_subscriber ?? 0,
        overage_price_non_subscriber: values.overage_price_non_subscriber ?? 0,
        metadata: values.metadata || "",
      };

      const hide = message.loading({ content: "保存中...", key: "save" });
      try {
        const res = await request.post("/api/admin/agent/pricing", payload);
        hide();
        if (res && res.data && res.data.success) {
          const updated = res.data.pricing;
          setData(prev => {
            const idx = prev.findIndex(p => p.id === updated.id);
            if (idx >= 0) {
              const copy = [...prev];
              copy[idx] = { ...copy[idx], ...updated } as PricingData;
              return copy;
            }
            return [updated as PricingData, ...prev];
          });
          message.success({ content: "保存成功", key: "save" });
          handleCancel();
        } else {
          message.error({ content: "保存失败", key: "save" });
        }
      } catch (e) {
        hide();
        message.error({ content: "保存失败", key: "save" });
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const formatPrice = (price: string | null) => (price ? `${price} ¥` : "-");

  const columns: ColumnsType<PricingData> = [
    {
      title: "AI人物 ID",
      dataIndex: "ai_person_id",
      key: "ai_person_id",
      width: 120,
    },
    {
      title: "AI人物名称",
      dataIndex: "ai_person_name",
      key: "ai_person_name",
    },
    {
      title: "需要订阅",
      dataIndex: "requires_subscription",
      key: "requires_subscription",
      render: (requires: boolean) => (
        <Tag color={requires ? "red" : "green"}>{requires ? "是" : "否"}</Tag>
      ),
    },
    {
      title: "订阅价格",
      dataIndex: "subscription_price",
      key: "subscription_price",
      render: (price: string | null) => formatPrice(price),
    },
    {
      title: "订阅用户按次价格",
      dataIndex: "per_use_price_subscriber",
      key: "per_use_price_subscriber",
      render: (price: string | null) => formatPrice(price),
    },
    {
      title: "非订阅用户按次价格",
      dataIndex: "per_use_price_non_subscriber",
      key: "per_use_price_non_subscriber",
      render: (price: string | null) => formatPrice(price),
    },
    {
      title: "免费配额类型",
      dataIndex: "free_quota_type",
      key: "free_quota_type",
      render: (type: string) => {
        const typeMap: Record<string, string> = {
          none: "无",
          daily: "每日",
          monthly: "每月",
          cycle: "计费周期",
        };
        return typeMap[type] || type;
      },
    },
    {
      title: "订阅用户免费配额",
      dataIndex: "free_quota_subscriber",
      key: "free_quota_subscriber",
      render: (n: number | null) => (n === null || n === undefined ? "-" : n),
    },
    {
      title: "非订阅用户免费配额",
      dataIndex: "free_quota_non_subscriber",
      key: "free_quota_non_subscriber",
      render: (n: number | null) => (n === null || n === undefined ? "-" : n),
    },
    {
      title: "订阅用户超额价格",
      dataIndex: "overage_price_subscriber",
      key: "overage_price_subscriber",
      render: (price: string | null) => formatPrice(price),
    },
    {
      title: "非订阅用户超额价格",
      dataIndex: "overage_price_non_subscriber",
      key: "overage_price_non_subscriber",
      render: (price: string | null) => formatPrice(price),
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (t: string | null) => (t ? new Date(t).toLocaleString() : "-"),
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
      render: (t: string | null) => (t ? new Date(t).toLocaleString() : "-"),
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      width: 100,
      render: (_, record) => (
        <Space size="small">
          <a onClick={() => openEdit(record)}>编辑</a>
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <Table
        columns={columns}
        dataSource={data}
        loading={loading}
        rowKey="id"
        pagination={false}
        scroll={{ x: 1400 }}
      />

      <Modal
        title={current ? `编辑 Agent ${current.ai_person_name}` : "编辑 Agent"}
        visible={editing}
        onCancel={handleCancel}
        onOk={handleOk}
        okText="保存"
        bodyStyle={{ height: "60vh", overflow: "auto" }}
      >
        <Form form={form} layout="vertical">
          <Form.Item label="AI人物 ID" name="ai_person_id" rules={[{ required: true, message: "请输入 AI 人物 ID" }]}>
            <InputNumber style={{ width: "100%" }} disabled />
          </Form.Item>

          <Form.Item label="需要订阅" name="requires_subscription" valuePropName="checked">
            <Switch />
          </Form.Item>

          <Form.Item label="订阅价格" name="subscription_price">
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>

          <Form.Item label="订阅用户按次价格（订阅后每次使用的价格）" name="per_use_price_subscriber">
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>

          <Form.Item label="非订阅用户按次价格" name="per_use_price_non_subscriber">
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>

          <Form.Item label="免费配额类型（每次重置次数的周期）" name="free_quota_type">
            <Select>
              <Option value="none">无</Option>
              <Option value="daily">每日</Option>
              <Option value="monthly">每月</Option>
            </Select>
          </Form.Item>

          <Form.Item label="订阅用户免费配额次数" name="free_quota_subscriber">
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>

          <Form.Item label="非订阅用户免费配额" name="free_quota_non_subscriber">
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>

          <Form.Item label="订阅用户超额价格（超出免费配额后的价格）" name="overage_price_subscriber">
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>

          <Form.Item label="非订阅用户超额价格" name="overage_price_non_subscriber">
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default AgentConfig;
